package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import com.sky.websocket.WebSocketServer;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.socket.sockjs.transport.session.WebSocketServerSockJsSession;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.RejectedExecutionException;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {
   @Autowired
   private OrderMapper orderMapper;
   @Autowired
   private OrderDetailMapper orderDetailMapper;
   @Autowired
   private AddressBookMapper addressBookMapper;
   @Autowired
   private ShoppingCartMapper shoppingCartMapper;
   @Autowired
   private UserMapper userMapper;
   @Autowired
   private WeChatPayUtil weChatPayUtil;
   @Autowired
   private WebSocketServer webSocketServer;
   @Transactional
   /*用户下单*/
    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //1.处理各种业务异常
        //1.地址簿为空
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if(addressBook==null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //2.购物车为空
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart=new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
        if(list.size()==0||list==null){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //2.向订单表中插入一条数据
        Orders orders=new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        //当前时间戳作为订单号
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        String address=addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail();
        orders.setAddress(address);
        orders.setUserId(userId);
        orderMapper.insert(orders);
        //3.向订单明细表中插入n条数据
        List<OrderDetail>orderDetailList=new ArrayList<OrderDetail>();
       for(ShoppingCart cart:list){
           OrderDetail orderDetail=new OrderDetail();
           BeanUtils.copyProperties(cart,orderDetail);
           orderDetail.setOrderId(orders.getId());
           orderDetailList.add(orderDetail);
       }
       orderDetailMapper.insertBatch(orderDetailList);
        //4.清空购物车
        shoppingCartMapper.deleteByUserId(userId);
        //5.封装VO返回结果
       OrderSubmitVO orderSubmitVO=OrderSubmitVO.builder()
               .id(orders.getId())
               .orderNumber(orders.getNumber())
               .orderAmount(orders.getAmount())
               .orderTime(orders.getOrderTime())
               .build();
       return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        /*//调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );*/
        JSONObject jsonObject=new JSONObject();

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
        //通过websocket向客户端浏览器推送消息 type-消息类型 orderId content-订单号
        Map map=new HashMap<>();
        map.put("type",1);//1-来单提醒 2-客户催单
        map.put("orderId",ordersDB.getId());
        map.put("content","订单号"+outTradeNo);
        String json=JSONObject.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }
   /*查询历史订单*/
    @Override
    public PageResult pageQuery(int pageNum, int pageSize, Integer status) {
        PageHelper.startPage(pageNum,pageSize);
        //当前Id
        Long userId = BaseContext.getCurrentId();
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(userId);
        ordersPageQueryDTO.setStatus(status);
        Page<Orders> page=orderMapper.pageQuery(ordersPageQueryDTO);
        List<OrderVO>list=new ArrayList<>();
        if(page!=null&&page.getTotal()>0){
            for(Orders orders:page)
        {  OrderVO orderVO=new OrderVO();
           BeanUtils.copyProperties(orders,orderVO);
           //订单详情
            List<OrderDetail> orderDetailList=orderDetailMapper.getByOrderId(orders.getId());
            orderVO.setOrderDetailList(orderDetailList);
            list.add(orderVO);
        }
        }
        return new PageResult(page.getTotal(),list);
    }
     /*查询历史订单详情*/
    @Override
    public OrderVO details(Long id) {
        //查询订单 orders
       Orders orders=orderMapper.getById(id);
       // 细节orderDetail
        List<OrderDetail> detail = orderDetailMapper.getByOrderId(id);
        //封装到orderVO
        OrderVO orderVO=new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDetailList(detail);
       return orderVO;
    }
   /*取消订单*/
    @Override
    public void userCancelById(Long id) throws Exception {
        Orders ordersDB=orderMapper.getById(id);
        //校验订单是否存在
        if(ordersDB==null)
        {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //已接单 和派送中 已完成 需要打电话协商
         if(ordersDB.getStatus()>2){
          throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //订单处于待接单状态下取消，需要进行退款 订单状态直接改为已取消
         Orders orders=new Orders();
         orders.setId(ordersDB.getId());
           if(ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)){
               //调用微信支付退款接口 这个地方因为我跳过支付了所以不能用
              /* weChatPayUtil.refund(
                       ordersDB.getNumber(), //商户订单号
                    ordersDB.getNumber(), //商户退款单号
                    new BigDecimal(0.01),//退款金额，单位 元
                    new BigDecimal(0.01));//原订单金额*/
               orders.setPayStatus(Orders.REFUND);
       }
            orders.setStatus(Orders.CANCELLED);
           orders.setCancelReason("订单取消");
           orders.setCancelTime(LocalDateTime.now());
           orderMapper.update(orders);
    }
/*再来一单*/
    @Override
    public void repetition(Long id) {
        //将原订单中的产品重新加入购物车中
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(id);
        Long userId = BaseContext.getCurrentId();
        //将订单详情对象转化为购物车对象 通过stream流的map映射
        List<ShoppingCart>shoppingCartList=orderDetails.stream().map(od->{
            ShoppingCart cart=new ShoppingCart();
             BeanUtils.copyProperties(od,cart,"id");
             cart.setUserId(userId);
             cart.setCreateTime(LocalDateTime.now());
             return cart;
        }).collect(Collectors.toList());


        shoppingCartMapper.insertBatch(shoppingCartList);
    }
    /*商家查询历史订单*/
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
      /* 输入订单号/手机号进行搜索，支持模糊搜索/根据订单状态进行筛选/下单时间进行时间筛选,搜索内容为空，提示未找到相关订单*/
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);
        //部分订单状态 需要额外返回订单菜品信息
        List<OrderVO>list=getOrderVOList(page);
        return new PageResult(page.getTotal(),list);
    }
   /* 各个状态的订单数量统计*/
    @Override
    public OrderStatisticsVO statistics() {
        //待接单
        Integer toBeConfirmed=orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        //待派送
        Integer confirmed=orderMapper.countStatus(Orders.CONFIRMED);
        //派送中
        Integer deliveryInProgress=orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);
        //封装
        OrderStatisticsVO orderStatisticsVO=new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }
    /*接单 更改状态信息*/
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Long orderId = ordersConfirmDTO.getId();
        Orders orders = Orders.builder()
                .id(orderId)
                .status(Orders.CONFIRMED)
                .build();
        orderMapper.update(orders);
    }
   /*拒单 将订单状态修改为已取消 如果用户已经付款 需要退款*/
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
        Long orderId = ordersRejectionDTO.getId();
        Orders ordersDB=orderMapper.getById(orderId);
        //订单只有存在且状态为2才可以拒单
        if(ordersDB==null||!ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED))
        {
            throw new RejectedExecutionException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders=new Orders();
        orders.setId(ordersDB.getId());
           if(ordersDB.getPayStatus().equals(Orders.PAID)){
               //调用微信支付退款接口 这个地方因为我跳过支付了所以不能用
              /* weChatPayUtil.refund(
                       ordersDB.getNumber(), //商户订单号
                    ordersDB.getNumber(), //商户退款单号
                    new BigDecimal(0.01),//退款金额，单位 元
                    new BigDecimal(0.01));//原订单金额*/
               orders.setPayStatus(Orders.REFUND);
       }
                orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.update(orders);

    }
   /*取消订单*/
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders ordersDB=orderMapper.getById(ordersCancelDTO.getId());
        //订单处于待接单状态下取消，需要进行退款 订单状态直接改为已取消
         Orders orders=new Orders();
         orders.setId(ordersCancelDTO.getId());
           if(ordersDB.getPayStatus().equals(Orders.PAID)){
               //调用微信支付退款接口 这个地方因为我跳过支付了所以不能用
              /* weChatPayUtil.refund(
                       ordersDB.getNumber(), //商户订单号
                    ordersDB.getNumber(), //商户退款单号
                    new BigDecimal(0.01),//退款金额，单位 元
                    new BigDecimal(0.01));//原订单金额*/
               orders.setPayStatus(Orders.REFUND);
       }
            orders.setStatus(Orders.CANCELLED);
           orders.setCancelReason(ordersCancelDTO.getCancelReason());
           orders.setCancelTime(LocalDateTime.now());
           orderMapper.update(orders);
    }
   /*派送订单*/
    @Override
    public void delivery(Long id) {
        /*将待派送的改为派送中*/
        Orders orders=orderMapper.getById(id);
        // 校验订单是否存在，并且状态为3
        if (orders== null || !orders.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(orders);
    }
   /*完成订单*/
    @Override
    public void complete(Long id) {
        //将派送中的改为已完成
        Orders orders=orderMapper.getById(id);
        if (orders== null || !orders.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(orders);
    }
   /*客户催单*/
    @Override
    public void reminder(Long id) {
        Orders orders=orderMapper.getById(id);
         if (orders== null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
         //通过websocket向客户端浏览器推送消息 type-消息类型 orderId content-订单号
        Map map=new HashMap<>();
        map.put("type",2);//1-来单提醒 2-客户催单
        map.put("orderId",orders.getId());
        map.put("content","订单号"+orders.getNumber());
        String json=JSONObject.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }

    private List<OrderVO> getOrderVOList(Page<Orders> page) {
        List<OrderVO> list=new ArrayList<>();
        List<Orders>ordersList=page.getResult();
        if(!CollectionUtils.isEmpty(ordersList))
        {
            for (Orders orders : ordersList) {
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                //订单菜品信息 订单包含的菜品，以字符串形式展示
               String orderDishes= getOrderDishesStr(orders);
               orderVO.setOrderDishes(orderDishes);
                list.add(orderVO);
            }
        }
        return list;
    }
/*订单包含的菜品，以字符串形式展示*/
    private String getOrderDishesStr(Orders orders) {

        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());
         // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；） stream流map映射方法
        List<String> orderDishes=orderDetailList.stream().map(od->{
            String s=od.getName()+'*'+od.getNumber();
            return s;
        }).collect(Collectors.toList());
        /*将 orderDishes 列表中的所有字符串元素使用逗号 , 连接成一个单个的字符串，
例如，如果 orderDishes 包含 ["宫保鸡丁*3", "鱼香肉丝*2"]，那么返回的字符串可能是 "宫保鸡丁*3,鱼香肉丝*2"。*/
        return String.join(",",orderDishes);
    }
    /**/

}
